import { IMiddleware } from '@midwayjs/core';
import { Body, Middleware } from '@midwayjs/decorator';
import { NextFunction, Context } from '@midwayjs/koa';
import { ErrCode } from '../common/ErrCode';
import { UserInfo } from '../entity/user.entity';
import { UserService } from '../service/user.service';

@Middleware()
export class UserMiddleware implements IMiddleware<Context, NextFunction> {

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      let isCheck = await this.checkUser(ctx);
      const result = await next();
      if(isCheck != true){
        return isCheck;
      }
      return result;
    };
  }

  public async checkUser(@Body() ctx:Context):Promise<any>{
    const userService = new UserService();
    let user:ErrCode|UserInfo = await userService.getUserInfo(ctx.userid);
    if((user as ErrCode) == ErrCode.USER_NOT_FOUND){
      return {code:user};
    }
    return true;
  }

  match(ctx: Context): boolean {
    // 下面的匹配到的路由不会执行此中间件
    let list = ['/api/reg','/api/login','/api/getOACode'];
    if (list.indexOf(ctx.path) === -1) {
      return true;
    }
  }
 
  static getName(): string {
    return 'report';
  }
}
